/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.taglibs.taxonomy;

import com.codemagi.servlets.model.*;
import com.codemagi.util.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.*;

/**
 * This class implements the &lt;tax:autocomplete&gt; tag, which presents a text box with a Javascript autocomplete select list to choose taxonomy terms
 *
 *  @version 1.0
 *  @author August Detlefsen for CodeMagi, Inc.
 */
public class TaxonomyAutocomplete extends TaxonomyTag {

    private String dVal = "";

    public void setDefault(String newValue) {
	dVal = newValue;
    }

    public int doStartTag() throws JspException {

	// sanity check                                                                                                   
	if (categoryId == null) throw new JspTagException("invalid categoryId specified");

	//determine the name for the select list
	String name = "taxonomy_" + categoryId;

	//default for id is the input name 
	if (Utils.isEmpty(id)) id = name;

	//quote the id now since we will use it multiple times
	String idq  = quote(id);

        try {
            // get what we need from the page                                                                               
            ServletRequest req = pageContext.getRequest();
            JspWriter out = pageContext.getOut();

            // start building up the tag                                                                                
            out.println();
            out.println("<input");
	    out.println("    type=\"text\" ");
	    out.println("    autocomplete=\"off\" ");
            out.println("    name=\"" + name + "\"");
            if (!Utils.isEmpty(id)) {
                out.println("    id=\"" + id + "\"");
            }

            //disable the form field if disabled is set                                                                
            if (disabled) {
                out.println("    readonly=\"readonly\"");
                out.println("    OnFocus=\"blur();\"");
                appendAttribute("style", "cursor:default;");
            }

            // include any attributes we've got here                                                                          
            printAttributes(out, attributes);

            //if this is a required field and it is not filled out, do something...                                 
            if ( !Utils.isEmpty((String)req.getAttribute("error_" + name + "_error")) ) {
                out.println("    class=\"" + markupClass + "_error\"");
            } else if ( !Utils.isEmpty(markupClass) ) {
                out.println("    class=\"" + markupClass + "\"");
            }

            // get the current selection.                                                                                  
            // NOTE that this is a single select list and should only have ONE item selected                 
            String selected = getParameter(name, (HttpServletRequest)req);
            log.debug("Select: selected: " + selected);

            if ( Utils.isEmpty(selected) || override ) {
                log.debug("Select: building chosen from Node");

                List<Term> selectedTerms = (node == null) ? new ArrayList<Term>() : node.getTerms(categoryId) ;
		log.debug("Selected terms: " + CollectionUtils.delimit(selectedTerms, "; "));

		StringBuffer selectedTermsList = new StringBuffer(selectedTerms.size() * 32);
		for (Term term : selectedTerms) {
		    if (selectedTermsList.length() > 0) selectedTermsList.append("; ");

		    selectedTermsList.append(term.getName());
		}

		selected = selectedTermsList.toString();
            }

	    log.debug("CHOSEN: " + selected);
	    out.println("    value=\"" + selected + "\"");

            // close off the tag
            out.println("/>");

	    //add the script to init the autocomplete
	    Set<String> allTerms = category.getTermNames();
	    StringBuffer quotedTerms = new StringBuffer(allTerms.size() * 32);
	    for (String term : allTerms) {
		if (quotedTerms.length() > 0) quotedTerms.append(",");
		quotedTerms.append("\"").append( quote(term) ).append("\"");
	    }

	    out.println("<script type=\"text/javascript\" src=\"/js/jquery/jquery.autocomplete.js\"></script>");
	    out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"/js/jquery/jquery.autocomplete.css\" />");
	    out.println("<script type=\"text/javascript\">");
	    out.println("jQuery().ready(function(){jQuery(\"#" + id + "\").autocomplete(" + id + "_opts,{multiple:true,autoFill:true,multipleSeparator:'; '});});");
	    out.println(" var " + id + "_opts = [" + quotedTerms + "];");
	    out.println("</script>");

        } catch (Exception ex) {
            log.debug("", ex);
            throw new JspTagException(ex.getMessage());
        }
        return SKIP_BODY;
    }

}
